Module# 12: Java IO Streams and
File Lecture#46: Random Access File
// Example 46.1: Reading from a RAF
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample
{
static final String FILEPATH ="NPTEL.txt";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile
file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
}
//
Example 46.2: Writing into a RAF
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample
{
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {
try {
writeToFile(FILEPATH, "Data Structures
and Algorithms Using Java", 41);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile
file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}
// Example 46.3: Reading and writing RAF
import java.io.*;
class RandomIO{
public static void main (String args[)){
RandomAccessFile
file = null;
try {
file = new
RandomAccessFile("rand.dat","rw");
// Writing to the file
file.writeChar('X');
file.writelnt(555);
file.writeDouble(3.1412);
file.seek (0);
// Go to the beginning
// Reading from the file
System.out.println(file.readChar());
// Continued on...
System.out.println(file.readlnt());
System.out.println(file.readDouble());
file.seek(2); // Go to the second item
System.out.println(file.readlnt());
// Go to the end and append false to the file
file.seek(file.length());
file.writeBoolean(false);
file. seek (4) ;
System.out.println(file.readBoolean());
file.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
// Example 46.4:
Appending to a RAF
import java.io.*;
class RandomAccess
{
static public void main(String args[]){
RandomAccessFile rFile;
try{
rFile = new RandomAccessFile("city.txt","rw");
rFile.seek(rFile.lenght()); // Go to the end
rFile.writeByte(“Joy with
Java\n"); //Append MUMBAI
rFile.close();
}
catch(IOException ioe){
System.out.println(ioe);
}
}
}
// Example 46.5:
Reading and writing objects (Defining objects)
/* This program
consists of three parts:
a) Define and creating objects
b) Writing objects into a file
c) Redaig objects
from the file
In the following, the
class files for each of ythe above parts are given.
*/
// Defining objects
import java.io.Serializable;
import java.util.*;
public class Student implements Serializable {
//default serialVersion
id
private static final long serialVersionUID = 1L;
private String firstName;
private String lasName;
private int age;
private int marks[] = new int[5];
public Student(String fname, String lname, int age, int smarks[]){
this.firstName = fname;
this.lastName = lname;
this.age = age;
this.marks = smarks;
}
public void setFirstName(String fname) {
this.firstName = fname;
}
public String getFirstName() {
return this.firstName;
}
public void setLastName(String lname) {
this.firstName = lname;
}
public String getLastName() {
return this.lastName;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
public void setMarks(int smarks[]) {
this.marks = smarks;
}
public int[] getMarks() {
return this.marks;
}
@Override
public String toString() {
return new StringBuffer(" \nFirst Name: ").append(this.first_name)
.append(" \nLast Name : ").append(this.last_name)
.append(" \nAge : ").append(this.age)
.append(" \nMarks : ")
.append(Arrays.toString(this.marks)).toString();
}
}
// Create objects and
writing into file
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class WriteObjectDemo
{
private static final String filepath="D:\\Java\\obj";
public static void main(String args[]) {
WriteObject objectIO = new ObjectIO();
int m[] = {50,47,89,65,78};
Student student
= new Student("John","Frost",22,m);
objectIO.writeObjectToFile(student);
}
public void writeObjectToFile(Object serObj) {
try {
FileOutputStream
fileOut = new FileOutputStream(filepath);
ObjectOutputStream
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(serObj);
objectOut.close();
System.out.println("The Object is successfully written to a file");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// Reading objects
from file
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class ReadObjectDemo{
private static final String filepath="D:\\Java\\obj";
public static void main(String args[]) {
ReadObject objectIO = new ReadObject();
objectIO.readObjectFromFile();
}
public void readObjectFromFile() {
try {
FileInputStream
fileIn = new FileInputStream(filepath);
ObjectInputStream
objectIn = new ObjectInputStream(fileIn);
Student student = (Student) objectIn.readObject();
System.out.println(student.toString());
objectIn.close();
System.out.println("The Object was succesfully read from the file");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}